﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO;
using System.Collections.ObjectModel;

/*
Copyright 2011 Mirosław M. Mączka

This file is part of MyChars.

    Flac2Wma is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace MyChars
{
    public sealed class ConfigFile
    {
        private string configDir="";
        private string configName = "";
        private string configPathName = "";
        //
        //private Form99 f99 = new Form99();
        //
        private struct _cell
        {
            public string plus;
            public string name;
            public string chars;
            //
            public _cell(string plus, string name, string chars)
            {
                this.plus = plus;
                this.name = name;
                this.chars = chars;
            }
        };

        private string[,] defaultData = {
            //{"","Polskie","Polish","ą ć ę ł ń ó ś ź ż"},
            //{"","Technika","Engineering","µ Ω ° √ ± ′ ″ ‴ ∏ ∑ × ∕ ÷ ∝ ≪ ≫ ≠ ≡ ≈ ♯ ♀ ♂ € ☠ ☢ ☣ ⚠ ⚡ ☯ ␆ ␈ ␉ ␊ ␍ ¼ ½ ¾ † ✗ ¶ ‡ ★ ␣ § ✓ “ • ← ↓ → ↑ ©"},

            {"+","Bułgarskie","Bulgarian","а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я"},
            {"","Chorwackie","Croatian","č ć đ š ž"},
            {"","Czeskie","Czech","á č ď é ě í ň ó ř š ť ú ů ý ž"},
            {"","Duńskie","Danish","å æ ø"},
            {"","Estońskie","Estonian","š ž õ ä ö ü"},
            {"","Fińskie","Finnish","å ä ö š ž"},
            {"","Francuskie","French","à á â ä æ ç è é ê ë î ï ô œ ù û ü ÿ ñ"},
            {"","Greckie","Greek","α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ σ ς τ υ φ χ ψ ω"},
            {"","Hiszpańskie","Spanish","á é í ñ ó ú ü ¿ ¡"},
            {"","Islandzkie","Icelandic","á ð é í ó ú ý þ"},
            {"","Irlandzkie","Irish","á é í ó ú"},
            {"","Litewskie","Lithuanian","ą č ę ė į š ų ū ž"},
            {"","Łotewskie","Latvian","ā č ē ģ ī ķ ļ ņ š ū ž"},
            {"","Niemieckie","German","ä ö ü ß ẞ"},
            {"","Norweskie","Norwegian","é è ê ó ò ô ì ù ỳ æ ø å"},
            {"","Portugalskie","Portuguese","á â ã à ç é ê í ó ô õ ú"},
            {"+","Rosyjskie","Russian","а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я"},
            {"","Rumuńskie","Romanian","ă â î ș ț"},
            {"","Runy","Runic","ᚠ ᚡ ᚢ ᚣ ᚤ ᚥ ᚦ ᚧ ᚨ ᚩ ᚪ ᚫ ᚬ ᚭ ᚮ ᚯ ᚰ ᚱ ᚲ ᚳ ᚴ ᚵ ᚶ ᚷ ᚸ ᚹ ᚺ ᚻ ᚼ ᚽ ᚾ ᚿ ᛀ ᛁ ᛂ ᛃ ᛄ ᛅ ᛆ ᛇ ᛈ ᛉ ᛊ ᛋ ᛌ ᛍ ᛎ ᛏ ᛐ ᛑ ᛒ ᛓ ᛔ ᛕ ᛖ ᛗ ᛘ ᛙ ᛚ ᛛ ᛜ ᛝ ᛞ ᛟ ᛠ ᛡ ᛢ ᛣ ᛤ ᛥ ᛦ ᛧ ᛨ ᛩ ᛪ ᛫ ᛬ ᛭ ᛮ ᛯ ᛰ"},
            {"+","Serbskie","Serbian","а б в г д ђ е ж з и ј к л љ м н њ о п р с т ћ у ф х ц ч џ ш"},
            {"","Serbskie","Serbian","č ć đ š ž"},
            {"","Słowackie","Slovak","á ä č ď é í ĺ ľ ň ó ô ŕ š ť ú ý ž"},
            {"","Słoweński","Slovenian","č š ž"},
            {"","Szwedzkie","Swedish","å ä ö"},
            {"","Tureckie","Turkish","â ç ğ i î ö ş ü û"},
            {"+","Ukraińskie","Ukrainian","а б в г ґ д е є ж з и і ї й к л м н о п р с т у ф х ц ч ш щ ь ю я"},
            {"","Węgierskie","Hungarian","á é í ó ö ő ú ü ű"},
            {"","Wietnamskie","Vietnamese","ă â đ ê ô ơ ư"},
            {"","Włoskie","Italian","à è é ì ò ù"},
            {"","","",""},
            {"","","",""},
            {"","","",""},
            {"","Akcenty","Grave","à ầ ằ è ề ḕ ì ǹ ò ồ ṑ ù ǜ ừ ẁ ỳ"},
            {"","","",""},
            {"","","",""},
            {"","Hebrajskie","Hebrew","ת תּ ש ר ק ץ צ ף פ פּ ע ס ן נ ם מ ל ך כ כּ י ט ח ז ו ה ד ג ב בּ א ﬩"},
            {"","","",""},
            {"","","",""},
            {"","","",""},
            {"","Waluty","Currecies","¤ ₳ ฿ ₵ ¢ ₡ ₢ ₠ $ ₫ ৳ ₯ € ƒ ₣ ₲ ₴ ₭ ₺ ℳ ₥ ₦ ₧ ₱ ₰ £ ₹ ₨ ₪ ₸ ₮ ₩ ¥ ៛"},
            {"","Matematyka","Math","± × ÷ ∕ − ∗ ∘ ∝ ∼ ≈ ≠ ≡ ∏ ∑ √ ∛ ∜ ℯ ℇ ℵ ⅇ ∅ ∞ ≮ ≯ ≤ ≥ ≰ ≱"},
            {"","Technika","Engineering","µ Ω ° ✓ ✗ ☐ ☑ ☒ 𐄂 ⍻ ❍ ⌗ ⎆ ♯ ☠ ☢ ☣ ✗ ¶ ‡ ★ • © ® ☠ ⚛ ⚡ ♲ ♻ ♀ ♂"},
            {"","Strzałki","Arrows","← → ↑ ↓ ↔ ↕ ↖ ↗ ↘ ↙ ↮ ⇐ ⇒ ⇑ ⇓ ⇔ ⇕ ⇖ ⇗ ⇘ ⇙ ⇍ ⇏ ⇎ ⟸ ⟹ ⟺ ⟵ ⟶ ⟷"},
            {"","Pogoda","Weather","☁ ☂ ☔ ☇ ☈ ☃ ⛄ ⛅ ☉ ☼ ☀ ☽ ☾"},
            {"","Ułamek","Fraction","½ ¼ ¾ ⅓ ⅔ ⅛ ⅜ ⅝ ⅞ ‰"},
            {"","Kultura","Culture","✚ ✛ ✜ ✙ ✝ ✞ ✟☓ ✠ ♰ ♱ ☩ ☦ ☨ ☧ ✡ ☪ ☫ ☬ ☭ ⚒ 卐 卍 ☸ ☥ ☘ ⚜ ⚘ ☯ ⚕ ⚚ ☤"},
            {"","Tekst","Text","※ ⸮ ◊ ▷ · ␢ ␣ ¶ § � § № º ª ′ “ « » ≪ ≫ ″ ‴"},
            {"","^ASCII","^ASCII","␀ ␁ ␂ ␃ ␄ ␅ ␆ ␇ ␈ ␉ ␊ ␋ ␌ ␍ ␎ ␏ ␐ ␑ ␒ ␓ ␔ ␕ ␖ ␗ ␘ ␙ ␚ ␛ ␜ ␝ ␞ ␟ ␡"},


            {"","","",""}
        };
        //
        //
        public ConfigFile()
        {
            configDir=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            configName = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + ".txt";
            configPathName = Path.Combine(configDir, configName);
        }
        //
        private string makeConfigText()
        {
            //
            bool isPL = false;
            if (System.Globalization.CultureInfo.CurrentCulture.TextInfo.CultureName.StartsWith("PL", StringComparison.CurrentCultureIgnoreCase))
            {
                isPL = true;
            }

            //
            List<_cell> l = new List<_cell>();
            if (!isPL) l.Add(new _cell("", "Polish", "ą ć ę ł ń ó ś ź ż"));
            for (int i = 0; i < defaultData.GetLength(0); i++)
            {
                if ("" == defaultData[i, 1]) continue;
                l.Add(new _cell(defaultData[i, 0], defaultData[i, isPL?1:2], defaultData[i, 3]));
            }
            //
            l.Sort((a, b) => a.name.CompareTo(b.name));
            //
            string s = "";
            //
            s += "# Encoding: UTF-8"+Environment.NewLine;
            s += "# Format: [+]name= a b c d" + Environment.NewLine;
            s += "#\r\n";
            foreach(_cell _c in l)
            {
                s += string.Format("{0}{1}={2}", _c.plus, _c.name, _c.chars) + Environment.NewLine;
            }
            //
            s += "# -=EOF=-" + Environment.NewLine;
            //
            return s;
        }
        //
        public bool CreateDefaultConfigFile(bool isForce)
        {
            //
            try
            {
                //
                if (isForce || !File.Exists(configPathName))
                {
                    File.WriteAllText(configPathName, makeConfigText(), Encoding.UTF8);
                }
                //
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message, "ERROR");
                return false;
            }
            //
            return true;
        }
        //
        public bool OpenConfigForEditing()
        {
            try
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = new System.Diagnostics.ProcessStartInfo(configPathName);
                p.StartInfo.UseShellExecute = true;
                p.Start();
                p.WaitForExit();
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(string.Format((string)MainWindow.GetLocalizedResource("label_EditConfigFile"), configPathName, e.Message), (string)MainWindow.GetLocalizedResource("label_Error"));
                return false;
            }
            return true;
        }
        //
        public bool LoadFromConfig(ObservableCollection<MainWindow._item> lst)
        {
            if (!CreateDefaultConfigFile(false))
            {
                return false;
            }
            //
            int lineNo = 0;
            lst.Clear();
            try
            {
                //
                string[] cfgs = File.ReadAllLines(configPathName, Encoding.UTF8);
                //
                int n = 0;
                foreach (string s in cfgs)
                {
                    lineNo++;
                    string l = s.Trim();
                    if ("" == l) continue;
                    if (l.StartsWith("#")) continue;
                    //
                    string[] pp = l.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    if (2 != pp.Length) continue;
                    pp[0] = pp[0].Trim(); pp[1] = pp[1].Trim();
                    if ("" == pp[0] || "" == pp[1]) continue;
                    //
                    if (n > 85) break;// limit
                    string[] ss = pp[1].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (0 == ss.Length) continue;//nie moze być pustych
                    lst.Add(new MainWindow._item(pp[0], ss));
                    n++;
                    //
                }
                //
            }
            catch (Exception e)
            {

                System.Windows.MessageBox.Show(string.Format((string)MainWindow.GetLocalizedResource("label_ErrorInConfigFile"), configName, lineNo, e.Message), (string)MainWindow.GetLocalizedResource("label_Error"));
                return false;
            }
            //
            return true;
        }
        //
    }//class
}//namespace
